﻿using System;
using RibbonLib.Interop;

namespace todo.Ribbon
{
    public class RibbonToggleButton : RibbonControl
    {
        private bool _checked;
        public event EventHandler OnClick;

        public RibbonToggleButton(RibbonUI ribbonUI, uint commandID) : base(ribbonUI, commandID)
        {
        }

        public bool Checked
        {
            get { return _checked; }
            set
            {
                if (_checked == value)
                {
                    return;
                }
                _checked = value;
                /*
                var boolValue = PropVariant.FromObject(value);
                var hr = _ribbonUI.Framework.SetUICommandProperty(
                    _commandID, ref RibbonProperties.BooleanValue,
                    ref boolValue);
                */
                var hr = _ribbonUI.Framework.InvalidateUICommand(_commandID, Invalidations.Property,
                        PropertyKeyRef.From(RibbonProperties.BooleanValue));
                if (!NativeMethods.Succeeded(hr))
                {
                    Console.WriteLine("??@");
                }
            }
        }

        public void FireOnClick(EventArgs e)
        {
            var handler = OnClick;
            if (handler != null) handler(this, e);
        }

        public override HRESULT UpdateProperty(ref PropertyKey key, PropVariantRef currentValue,
                                               ref PropVariant newValue)
        {
            if (key == RibbonProperties.BooleanValue)
            {
                newValue.SetBool(_checked);
                return HRESULT.S_OK;
            }


            return base.UpdateProperty(ref key, currentValue, ref newValue);
        }

        public override HRESULT Execute(ExecutionVerb verb, PropertyKeyRef key,
                                        PropVariantRef currentValue,
                                        IUISimplePropertySet commandExecutionProperties)
        {
            if (verb == ExecutionVerb.Execute)
            {
                FireOnClick(EventArgs.Empty);
            }
            return HRESULT.S_OK;
        }
    }
}